package com.hxkj.client.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hxkj.client.service.*;
import com.hxkj.domain.po.*;
import com.platform.common.domain.exception.CustomException;
import com.platform.common.domain.exception.CustomMessageException;
import com.platform.common.domain.result.ResultDataStruct;
import com.platform.common.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.hxkj.domain.Constant.CmsConstants.*;

@Slf4j
public abstract class AbstarctLabelService {

    private static final String UNIVERAL_SITE = "UNIVERAL_SITE";

    private static final String WEBSITE_ADD = "WEBSITE_ADD";

    private static final String COLUMN_SITE = "column_";

    @Autowired
    private TemplteServiceClient templteServiceClient;

    @Autowired
    private ColumnServiceClient columnServiceClient;

    @Autowired
    private TagsServiceClient tagsServiceClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WebsiteAddrServiceClient websiteAddrServiceClient;

    @Autowired
    private LeafletServiceClient leafletServiceClient;

    @Autowired
    private UniversalServiceClient universalServiceClient;

    @Autowired
    private ArticleServiceClient articleServiceClient;

    @Autowired
    private ContentMappingServiceClient contentMappingServiceClient;

    @Autowired
    private ContentServiceClient contentServiceClient;


    /*****
     * 获取单页详情存入环境变量
     * ****/
    protected Leaflet getLeaflet(FreeMarker freeMarker) throws Exception {
        Long leafletId = freeMarker.getArticleId();
        if (null == leafletId) {
            Leaflet l = new Leaflet();
            l.setLeafletId(-2L);
            return l;
        }
        Leaflet leaflet = new Leaflet();
        leaflet.setLeafletId(leafletId);
        leaflet.setSiteId(freeMarker.getSiteId());
        //单页详情
        Leaflet leaflet_ = leafletServiceClient.getLeafletByStatus(leaflet).getData();
        return leaflet_;
    }


    /**
     * 获取当前分类信息存入环境变量
     ***/
    protected Column getColumn(FreeMarker freeMarker) throws Exception {
        if (null == freeMarker.getColumnId()) {
            Column column = new Column();
            column.setColumnId(-2L);
            return column;
        }

       /* String columnKey = COLUMN_SITE+freeMarker.getSiteId()+"_"+freeMarker.getColumnId();
        if(redisTemplate.hasKey(columnKey)) {
            Column column = (Column) redisTemplate.opsForValue().get(columnKey);
            if(null != column) return column;
        }*/
        Column column = new Column();
        column.setColumnId(freeMarker.getColumnId());
        column.setSiteId(freeMarker.getSiteId());
        //Mr.zheng:封装当前选中的分类信息
        column = columnServiceClient.getColumn(column);
        return column;

    }

    /***
     * 获取当前tag信息存入环境变量
     * ****/
    protected Tags getTags(FreeMarker freeMarker) throws Exception {
        if (null == freeMarker.getTagsId()) {
            Tags t = new Tags();
            t.setTagsId(-2L);
            return t;
        }
        Tags tags = new Tags();
        tags.setTagsId(freeMarker.getTagsId());
        tags.setSiteId(freeMarker.getSiteId());
        //Mr.zheng:封装当前选中的分类信息
        tags = tagsServiceClient.getTags(tags);
        return tags;

    }

    /**
     * 获取模板
     *
     * @param siteId 站点id
     * @param templateId 模板id
     * @return
     * @throws Exception
     */
    protected Templet getTemplet(Long siteId,Long templateId) throws Exception {
        try {
            //先从redis缓存中获取,取不到再调远程接口
            //因为模板管理那边放到redis缓存时key里面拼接了siteId,所以也需要传入站点id
            Templet templet = (Templet) redisTemplate.opsForValue().get("templet_"+siteId+"_" + templateId);
            if (templet != null) {
                return templet;
            }
            templet = new Templet();
            templet.setTempletId(templateId);
            templet.setDelTag((byte) 0);
            ResultDataStruct<Templet> resultDataStruct = templteServiceClient.get(templet);
            if(resultDataStruct.getCode()==200) {
                return resultDataStruct.getData();
            }else{
                throw new CustomMessageException(resultDataStruct.getCode(),resultDataStruct.getMessage());
            }
        }catch (CustomMessageException | CustomException e){
            throw e;
        }catch (Exception e){
            log.error("获取模板出错",e);
            throw new CustomMessageException(400,"获取模板出错");
        }
    }

    /***
     *
     * ***/
    protected Templet getTemplteContent(Templet templet) throws Exception {
        Templet templetData = (Templet) redisTemplate.opsForValue().get("templet_" + templet.getSiteId() + "_" + templet.getPath());
        if (templetData != null) return templetData;
        Templet newTemplet = new Templet();
        newTemplet.setPath(templet.getPath());
        newTemplet.setDelTag((byte) 0);
        newTemplet.setSiteId(templet.getSiteId());
        Templet templet1 = templteServiceClient.getTemplet(templet);
        if (null != templet1)
            redisTemplate.boundValueOps("templet_" + templet1.getSiteId() + "_" + templet1.getPath());
        return templet1;
    }

    /****
     * 获取url规则配置
     * 如果redis换成不存在;则从数据库中查询;如若存在;则从缓存中获取
     * **/
    protected WebsiteAddr getWebSiteAddr(FreeMarker freeMarker) throws Exception {
       /* WebsiteAddr websiteAddr = (WebsiteAddr) redisTemplate.opsForValue().get(WEBSITE_ADD + freeMarker.getSiteId());
        if (websiteAddr != null) return websiteAddr;*/
        WebsiteAddr websiteAddrData = new WebsiteAddr();
        websiteAddrData.setDelTag(0L);
        websiteAddrData.setSiteId(freeMarker.getSiteId());
        WebsiteAddr websiteAddr = websiteAddrServiceClient.get(websiteAddrData).getData();
        return websiteAddr;
    }

    /****
     * 获取站点信息存入环境变量
     * *****/
    protected SiteUniversal getSiteUniversal(FreeMarker freeMarker) throws Exception {
       /* SiteUniversal siteUniversal = (SiteUniversal) redisTemplate.opsForValue().get(UNIVERAL_SITE + freeMarker.getSiteId());
        if (siteUniversal != null) return siteUniversal;*/
        SiteUniversal siteUniversalData = new SiteUniversal();
        siteUniversalData.setSiteId(freeMarker.getSiteId());
        ResultDataStruct<SiteUniversal> resultStruct = universalServiceClient.get(siteUniversalData);
        if(resultStruct.getCode() != 200){
            throw new CustomMessageException(resultStruct.getCode(),resultStruct.getMessage());
        }
        return resultStruct.getData();
    }

    /*****
     * 获取文章详情存入环境变量
     * ***/
    protected Article getArticle(FreeMarker freeMarker) throws Exception {
        Long articleId = freeMarker.getArticleId();
        if (null == articleId) {
            Article art = new Article();
            art.setColumnId(-2L);
            art.setArticleId(-2L);
            return art;
        }
        Article article_ = new Article();
        article_.setArticleId(articleId);
        article_.setSiteId(freeMarker.getSiteId());

        //  文章详情
        Article article = articleServiceClient.getArticle(article_).getData();
        // 防止模板中没有做空值处理报错
        if (null == article) {
            article = new Article();
            article.setArticleId(-2L);
            article.setColumnId(-2L);
            return article;
        }
        //判断该文章所在分类是否有扩展属性
        ContentMapping contentMapping = new ContentMapping();
        contentMapping.setColumnId(article.getColumnId());
        ResultDataStruct<List<ContentMapping>> resultDataStruct1 = contentMappingServiceClient.getContentMappingList(contentMapping);
        if (resultDataStruct1.getData() != null && resultDataStruct1.getData().size() > 0) {
            //该分类有扩展属性
            List<ContentMapping> contentMappingList = resultDataStruct1.getData();
            setContentMap(article, contentMappingList);
        }
        //Mr.zheng:如果有外链，则将文章详情的页面路径设置为外链路径
        if (StringUtils.isNotEmpty(article.getExternalLink())) {
            article.setManuscriptPath(article.getExternalLink());
        }
        article.setDateFormat(DateUtils.toDateToString(new Date(article.getCreateTime()), "yyyy-MM-dd"));
        return article;

    }


    public void setContentMap(Article article, List<ContentMapping> contentMappingList) throws Exception {
        Content content = new Content();
        content.setArticleId(article.getArticleId());
        content.setSiteId(article.getSiteId());
        ResultDataStruct<Content> resultDataStruct2 = contentServiceClient.getContent(content);
        if (resultDataStruct2.getData() != null) {
            content = resultDataStruct2.getData();
        }
        String json = JSONObject.toJSONString(content);
        JSONObject jsonObject = JSONObject.parseObject(json);
        Map<String, String> map = new HashMap<>();
        for (ContentMapping Mapping : contentMappingList) {
            if (null != Mapping && Mapping.getContentName() != null) {
                map.put(Mapping.getCustomName(), jsonObject.get(Mapping.getContentName()) == null ? "" : jsonObject.get(Mapping.getContentName()).toString());
            }
        }
        article.setMap(map);

    }

    public void saveManuscriptPath(String manuscriptPath, FreeMarker freeMarker) throws Exception {
        //Mr.zheng:1为频道模板调用
        if (freeMarker.getStatus() == CHANNEL) {

        }
        //Mr.zheng:2为文章详情模板调用
        if (freeMarker.getStatus() == ARTICLEDETAIL) {
            saveArticlePath(manuscriptPath, freeMarker);
        }
        //Mr.zheng:3为分类列表模板调用
        if (freeMarker.getStatus() == COLUMNLIST && freeMarker.getPageNum() == 1) {
            saveColumnPath(manuscriptPath, freeMarker);
        }
        //Mr.zheng:4为单页模板调用
        if (freeMarker.getStatus() == LEAFLET) {
            saveLeafletPath(manuscriptPath, freeMarker);
        }
        //Mr.zheng:5为聚合详情模板调用
        if (freeMarker.getStatus() == TAGSDEATIL && freeMarker.getPageNum() == 1) {
            saveTagsPath(manuscriptPath, freeMarker);
        }

    }

    private void saveArticlePath(String manuscriptPath, FreeMarker freeMarker) throws Exception {
        Article article = new Article();
        article.setArticleId(freeMarker.getArticleId());
        article.setSiteId(freeMarker.getSiteId());
        article.setManuscriptPath(manuscriptPath);
        articleServiceClient.modifyArticleAsPath(article);
    }

    private void saveColumnPath(String manuscriptPath, FreeMarker freeMarker) throws Exception {
        Column column = new Column();
        column.setColumnId(freeMarker.getColumnId());
        column.setSiteId(freeMarker.getSiteId());
        column.setManuscriptPath(manuscriptPath);
        columnServiceClient.modifyTemptId(column);
    }

    private void saveLeafletPath(String manuscriptPath, FreeMarker freeMarker) throws Exception {
        Leaflet leaflet = new Leaflet();
        leaflet.setLeafletId(freeMarker.getLeafletId());
        leaflet.setSiteId(freeMarker.getSiteId());
        leaflet.setManuscriptPath(manuscriptPath);
        leafletServiceClient.updateLeaflet(leaflet);
    }

    private void saveTagsPath(String manuscriptPath, FreeMarker freeMarker) throws Exception {
        Tags tagsInfo = new Tags();
        tagsInfo.setSiteId(freeMarker.getSiteId());
        tagsInfo.setTagsId(freeMarker.getTagsId());
        tagsInfo.setManuscriptPath(manuscriptPath);
        tagsServiceClient.modifyTags(tagsInfo);
    }

}
